import requests
import re

# 接口配置
BASE_URL = "http://0.0.0.0:8585/v1/chat_messages"
HEADERS = {
    "Accept": "application/json",
    "Content-Type": "application/json"
}

# 输入数据
input_data = [
    ("wmCPWCGQAAKbYLnKOm8OcsXSWMTRkN5A", "yanwendi_6040", "2025-08-09 19:11:47"),
    ("wmCPWCGQAAAahKgIIiSpUUgZ4kbVxLNg", "zhangyu76_6051", "2025-08-10 16:41:56"),
    ("wmCPWCGQAA3I1hjd9aKnexvpTn1Mu1Sw", "yanwendi_6262", "2025-08-10 11:21:41"),
    ("wmCPWCGQAA1cggDcoWRQKc8P7YYAp-iQ", "zhangyu76_6052", "2025-08-11 14:49:37"),
    ("wmCPWCGQAAp1nrth8OCkWryNXL-tebtg", "zhangyu76_6038", "2025-08-11 13:29:36"),
    ("wmCPWCGQAAL6-D664in693Y_UmFTG6Ww", "zhangyu76_6034", "2025-08-11 12:59:18"),
    ("wmCPWCGQAATjyaqFBS4ZFBupAQQcpcYQ", "yanwendi_6040", "2025-08-11 08:34:04"),
    ("wmCPWCGQAAKVwQizibhZSJyk4TXZG4Tg", "zhangyu76_6052", "2025-08-11 07:02:10"),
    ("wmCPWCGQAAUyok5g9B6GTC8e2stPpPGQ", "zhangyu76_6052", "2025-08-10 07:05:05"),
    ("wmCPWCGQAA00ZS_0wnt6DcYWXrzuWfqQ", "zhangyu76_6297", "2025-08-11 10:07:10")
]

# 输出列表
output_md = []

for idx, (customer_external_id, td_bot_user_id, created_at_str) in enumerate(input_data):
    print(f"正在处理第 {idx + 1} 条数据...")

    params = {
        "customerExternalUserId": customer_external_id,
        "td_bot_user_id": td_bot_user_id,
        "datetime_after": created_at_str
    }

    try:
        response = requests.get(BASE_URL, params=params, headers=HEADERS, timeout=10)
        response.raise_for_status()
        data = response.json()

        messages = data.get("messages", [])
        if not messages:
            print(f"用户 {customer_external_id} 无消息")
            continue

        # 构建用户块
        user_section = f"# 用户{idx + 1}\n"
        user_section += f"## 用id：\n{customer_external_id}\n"
        user_section += f"## 销售id：\n{td_bot_user_id}\n\n"

        for msg in messages:
            role = msg["role"]
            content = msg["content"]

            # 关键修复：将换行符替换为空格，并压缩多余空白
            content_oneline = re.sub(r'\s+', ' ', content.replace('\n', ' ').replace('\r', ' ')).strip()

            user_section += f"{role}：{content_oneline}\n"

        output_md.append(user_section)
        output_md.append("\n\n\n\n\n")  # 5个换行分隔

    except requests.exceptions.RequestException as e:
        print(f"请求失败：{customer_external_id}，错误：{e}")
        continue
    except Exception as e:
        print(f"解析失败：{customer_external_id}，错误：{e}")
        continue

# 合并输出，去掉末尾多余的换行
final_output = "".join(output_md).rstrip()

with open("chat_output.md", "w", encoding="utf-8") as f:
    f.write(final_output)

print("✅ 所有数据处理完成，已保存至 chat_output.md")